#!/usr/bin/env python3
# coding:utf-8
# 'yak.py' is a top-level config/build command line tool for YAK
#
# You don't have to use yak.py, you can use make directly
# (or use make in an IDE)

import sys
import os
import argparse
import subprocess

import requests
import json

class FatalError(RuntimeError):
    """
    Wrapper class for runtime errors that aren't caused by bugs in yak.py or the build proces.s
    """
    pass

# Use this Python interpreter for any subprocesses we launch
PYTHON=sys.executable
PY3="python3"
PROJECT_PATH="./"

def check_environment():
    """
    Verify the environment contains the top-level tools we need to operate
    """
    detected_yak_path = os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))
    if "YAK_PATH" in os.environ:
        set_yak_path = os.path.realpath(os.environ["YAK_PATH"])
        if set_yak_path != detected_yak_path:
            print("WARNING: YAK_PATH environment variable is set to %s but yak.py path indicates YAK directory %s. Using the environment variable directory, but results     may be unexpected..."
                % (set_yak_path, detected_yak_path))
    else:
        print("Setting YAK_PATH environment variable: %s" % detected_yak_path)
        os.environ["YAK_PATH"] = detected_yak_path

    if "PROJECT_PATH" in os.environ:
        os.environ["PROJECT_PATH"] = os.path.realpath(os.environ["PROJECT_PATH"])
        print("Setting PROJECT_PATH enveironment variable: %s" % os.environ["PROJECT_PATH"])

def _run_tool(tool_name, args, cwd):
     def quote_arg(arg):
         """ Quote 'arg' if necessary """
         if " " in arg and not (arg.startswith('"') or arg.startswith("'")):
             return "'" + arg + "'"
         return arg
     display_args = " ".join(quote_arg(arg) for arg in args)
     print("Running %s with output directory %s" % (tool_name, quote_arg(cwd)))
     print('Executing "%s"...' % str(display_args))
     try:
         # Note: we explicitly pass in os.environ here, as we may have set YAK_PATH there during startup
         subprocess.check_call(args, env=os.environ) # comment cwd
     except subprocess.CalledProcessError as e:
         raise FatalError("%s failed with exit code %d" % (tool_name, e.returncode))

def main():
    print("build testc project")
    if sys.version_info[0] != 3 or sys.version_info[1] < 6:
        raise FatalError("YAK currently only supports Python 3.6, and this is Python %d.%d.%d. Search for 'Setting the Python Interpreter' in the YAK docs for some tips to  handle this." % sys.version_info[:3])
    parser = argparse.ArgumentParser(description='YAK tool')
    args = parser.parse_args()
    check_environment()

    project_path = os.environ["PROJECT_PATH"]

    cwd = ""
    os.chdir(project_path)
    yak_args = ["docker-compose", "up", "--build"]

    _run_tool(PY3, yak_args, cwd)


if __name__ == "__main__":
    main()

